/**
 * 获取当前用户信息API路由
 */
import { NextRequest, NextResponse } from 'next/server';
import { getCurrentUser } from '@/middleware/auth';
import { AuthService } from '@/lib/auth';
import { getDb } from '@/lib/db';
import { User } from '@/lib/db/auth-schema';

export async function GET(request: NextRequest) {
  try {
    // 首先尝试从中间件获取用户信息
    let currentUser = getCurrentUser(request);
    
    // 如果中间件没有设置用户信息，直接验证 token
    if (!currentUser) {
      // 从 cookie 或 Authorization header 中获取 token
      const authHeader = request.headers.get('authorization');
      const tokenFromHeader = authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : null;
      const tokenFromCookie = request.cookies.get('auth-token')?.value;
      
      const token = tokenFromHeader || tokenFromCookie;
      
      if (!token) {
        return NextResponse.json(
          { error: '未认证', code: 'UNAUTHORIZED' },
          { status: 401 }
        );
      }
      
      // 验证 token
      const verification = await AuthService.verifyToken(token);
      if (!verification.valid || !verification.payload) {
        return NextResponse.json(
          { error: '认证无效', code: 'INVALID_TOKEN' },
          { status: 401 }
        );
      }
      
      currentUser = verification.payload;
    }

    // 从数据库获取完整用户信息
    const db = await getDb();
    const userResult = await db.findOne<User>('users', { id: currentUser.userId });
    
    if (!userResult.success || !userResult.data) {
      return NextResponse.json(
        { error: '用户不存在', code: 'USER_NOT_FOUND' },
        { status: 404 }
      );
    }

    const user = userResult.data;
    
    // 返回用户信息（不包含敏感数据）
    return NextResponse.json({
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        displayName: user.display_name,
        role: user.role,
        avatar: user.avatar,
        status: user.status,
        emailVerified: user.email_verified,
        loginCount: user.login_count,
        lastLogin: user.last_login,
        createdAt: user.created_at
      }
    });
  } catch (error) {
    console.error('获取用户信息API错误:', error);
    return NextResponse.json(
      { error: '服务器内部错误', code: 'INTERNAL_ERROR' },
      { status: 500 }
    );
  }
}

// 不允许其他HTTP方法
export async function POST() {
  return NextResponse.json(
    { error: '方法不允许', code: 'METHOD_NOT_ALLOWED' },
    { status: 405 }
  );
}